/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rmi;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.UnknownHostException;
import java.lang.NullPointerException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import shared.Monitoring;

/**
 *
 * @author xarckane
 */
public class CtlCache {

    private HashMap<User, Monitoring> cache = new HashMap<User, Monitoring>();

    public synchronized Monitoring getMonito(String ipClient, String ipServ) throws RemoteException, NotBoundException, UnknownHostException {

        Monitoring monito = null;
        Set set = this.cache.entrySet();
        Iterator i = set.iterator();
        boolean exist = false;
        if (this.cache.isEmpty()) {
            
            monito = RmiClient.getMonito(ipServ);
            if (monito != null) {
                this.cache.put(new User(ipClient), monito);
            }

        } else {
            while (i.hasNext()) {
                Map.Entry me = (Map.Entry) i.next();
                Calendar cal = (Calendar) Calendar.getInstance().clone();
                cal.add(Calendar.MINUTE, -1);

                if (!(((User) me.getKey()).getIp().equalsIgnoreCase(ipClient))) {
                    if (((User) me.getKey()).getTime().compareTo(cal.getTime()) < 0) {
                        this.cache.remove((User) me.getKey());
                    }
                } else {
                    exist = true;
                    String ip=null;
                    try{
                        ip=this.cache.get((User) me.getKey()).getServ();
                    }catch(java.rmi.ConnectException ex){
                        this.cache.remove((User) me.getKey());
                        throw ex; 
                    }
                    if (ip.equals(ipServ)) {
                        return this.cache.get((User) me.getKey());
                    } else {
                        monito = RmiClient.getMonito(ipServ);
                        if (monito != null) {
                            this.cache.put(new User(ipClient), monito);
                        }
                    }

                }
                if (!exist) {
                    monito = RmiClient.getMonito(ipServ);
                    this.cache.put(new User(ipClient), monito);

                }
            }
        }
       
        return monito;
    }
}
